package com.easycar.common.util;

import android.app.Application;
import android.os.Looper;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


/**
 * 崩溃日志收集
 */
public class UnCExcHandler  implements Thread.UncaughtExceptionHandler {
    public static final long DELETE_TIME_MARK = 1000 * 3600 * 24 * 7;

    private Thread.UncaughtExceptionHandler defaultHandler;
    private UnCExcCustomJob unCExcCustomJob;
    private Application application;


    public UnCExcHandler(Application application) {
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        this.application = application;
    }

    public UnCExcHandler(Application application, UnCExcCustomJob unCExcCustomJob) {
        this.unCExcCustomJob = unCExcCustomJob;
        this.application = application;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && null != defaultHandler) {
            /**
             * dose not set handle exception, what use system default uncaughtException
             */
            defaultHandler.uncaughtException(thread, ex);
        } else {
            if (null != defaultHandler) {
                defaultHandler.uncaughtException(thread, ex);
            }
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex {@link Throwable}
     * @return boolean true 处理过的, false 未处理
     */
    private boolean handleException(final Throwable ex) {
        if (ex == null) {
            return false;
        }
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                String errorLog = StringUtils.exception2String(ex);
                saveLogAtSDPath(errorLog);
                if (null != unCExcCustomJob) {
                    unCExcCustomJob.customJob(ex);
                }
                GLog.e("Log "+"UnCExcHandlerException"+errorLog);
                ExitApp.killAppProcess();
                Looper.loop();
            }
        }.start();
        return true;
    }

    private void saveLogAtSDPath(String errorLog) {
        String savePath = SDCardUtil.SD_PATH_EXTERNAL + File.separator+SDCardUtil.COMPANY+File.separator
                + application.getPackageName() +  File.separator
                + "errorLog" + File.separator;
        File folder = new File(savePath);
        String saveLogPath = savePath + "log_" + new SimpleDateFormat("yyyy_MM_dd_HH", Locale.CHINA).format(new Date())
                + ".log";
        File logFile = new File(saveLogPath);
        GLog.e("Log savePath: "+saveLogPath);
        try {
            if (!folder.exists()) {
                folder.mkdirs();
            }
            cleanFolderOldLogs(folder);
            if (!logFile.exists()) {
                logFile.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(logFile, true);
            BufferedWriter bufferWriter = new BufferedWriter(fileWriter);
            bufferWriter.write(errorLog);
            bufferWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void cleanFolderOldLogs(File savePath) {
        long nowTime = System.currentTimeMillis();
        if (savePath.isDirectory()) {
            File[] files = savePath.listFiles();
            if (null != files) {
                for (File file : files) {
                    if (file.exists() && (nowTime - file.lastModified() > DELETE_TIME_MARK)) {
                        file.delete();
                    }
                    file = null;
                }
            }
            files = null;
        }
    }
}
